import { useEffect, useState } from "react";
import storage from "@/utils/storage";
import { ReactNode } from "react";
import { Navigate } from "react-router-dom";

interface Props {
  children: ReactNode;
}

const AuthRoute = ({ children }: Props) => {
  const [hasToken, setHasToken] = useState<boolean>(storage.getCache('token')!== null);

  useEffect(() => {
    const handleStorageChange = (event:any) => {
      if (event.key === 'token') {
        const newToken = storage.getCache('token');
        setHasToken(newToken!== null);
      }
    };

    window.addEventListener('storage', handleStorageChange);

    return () => {
      window.removeEventListener('storage', handleStorageChange);
    };
  }, []);
  console.log(hasToken);
  
  if (hasToken) {
    return <> { children } </>;
  } else {
    return <Navigate to='./login' replace />;
  }
};

export default AuthRoute;